package org.xxpay.pay.channel.hmapay;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.domain.api.AbstractRes;
import org.xxpay.core.common.domain.api.ApiBuilder;
import org.xxpay.core.common.domain.api.PayRes;
import org.xxpay.core.common.domain.api.msg.QueryRetMsg;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.util.XXPayUtil;
import org.xxpay.core.common.vo.DBApplicationConfig;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;
import org.xxpay.pay.mq.BaseNotify4MchPay;

import java.util.TreeMap;

/**
 * @author: pangxiaoyu
 * @date: 2020年2月25日15:40:47
 */
@Service
public class HmapayPaymentService extends BasePayment {

    @Autowired
    public BaseNotify4MchPay baseNotify4MchPay;

    private static final MyLog _log = MyLog.getLog(HmapayPaymentService.class);

    @Override
    public String getChannelName() {
        return HmapayConfig.CHANNEL_NAME;
    }

    /**
     * 支付
     * @param payOrder
     * @return
     */
    @Override
    public AbstractRes pay(PayOrder payOrder) {
        String channelId = payOrder.getChannelId();
        AbstractRes retObj;
        switch (channelId) {
            case HmapayConfig.CHANNEL_NAME_ALI_H5 :
                retObj = doPay(payOrder, HmapayConfig.PAY_TYPE);
                break;
            case HmapayConfig.CHANNEL_NAME_ALI_QR :
                retObj = doPay(payOrder, HmapayConfig.PAY_TYPE);
                break;
            default:
                return ApiBuilder.bizError("不支持的渠道[channelId="+channelId+"]");
        }
        return retObj;
    }

    /**
     * 支付
     * @param payOrder
     * @return
     */
    public AbstractRes doPay(PayOrder payOrder, String type) {
        HmapayConfig hmapayConfig = new HmapayConfig(getPayParam(payOrder));
        PayRes retObj = ApiBuilder.buildSuccess(PayRes.class);
        TreeMap<String, Object> paramMap = new TreeMap<>();
        // 接口类型
        paramMap.put("pid", hmapayConfig.getMchId());
        paramMap.put("out_trade_no", payOrder.getPayOrderId());
        paramMap.put("money", AmountUtil.convertCent2Dollar(payOrder.getAmount()+""));
        paramMap.put("type", type);
        if(StringUtils.isBlank(payOrder.getClientIp()) || "null".equalsIgnoreCase(payOrder.getClientIp())) {
            paramMap.put("userip", "127.0.0.1");
        }else {
            paramMap.put("userip", payOrder.getClientIp());
        }
        DBApplicationConfig dbConfig = getDBApplicationConfig();
        paramMap.put("userid", payOrder.getMchId()+"");
        paramMap.put("notify_url", super.getNotifyUrl(getChannelName(), dbConfig));  // 回调地址
        paramMap.put("return_url", super.getReturnUrl(getChannelName(), dbConfig));
        try {
            // 生成签名
            String sign = HmaUtil.createSign(paramMap, hmapayConfig.getKey());
            paramMap.put("sign", sign);

            String toPayUrl = hmapayConfig.getReqUrl() + "/mobile/chongzhi/submit";
            paramMap.put("toPayUrl", toPayUrl);
            String toUrl = dbConfig.getConfig4PayUrl() + "/hmapay/hmapay_alipay.htm?" + XXPayUtil.genUrlParams(paramMap);
//            toUrl = URLEncoder.encode(toUrl);
            _log.info("{}请求路径:{}, 请求参数:{}", getChannelName(), toPayUrl, paramMap);
            JSONObject payInfo = new JSONObject();
            payInfo.put("payType", type);           // 支付方式
            payInfo.put("payJumpUrl", toUrl);      // 可以通过该地址跳转到支付中心界面完成支付(URL)
            StringBuffer payForm = new StringBuffer();

            payForm.append("<form style=\"display: none\" action=\""+ toPayUrl +"\" method=\"post\">");
            paramMap.keySet().stream().forEach(key ->
                    payForm.append("<input type=\"text\" name=\""+key+"\" value=\""+paramMap.get(key)+"\">")
            );
            payForm.append("<input type=\"submit\" value=\"立即支付\" style=\"display:none\" >");
            payForm.append("</form>");
            payForm.append("<script>document.forms[0].submit();</script>");

            retObj.setPayMethod(PayConstant.PAY_METHOD_FORM_JUMP);
            retObj.setPayUrl(payForm.toString());
            int updateCount = commonService.payOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
            _log.info("[{}]更新订单状态为支付中:payOrderId={},payUrl={},payType={},result={}", getChannelName(), payOrder.getPayOrderId(), toPayUrl, type, updateCount);
            return retObj;
        } catch (Exception e) {
            _log.error(e, "");
            return ApiBuilder.bizError("操作失败!");
        }
    }

    /**
     * 查询订单
     * @param payOrder
     * @return
     */
    @Override
    public QueryRetMsg query(PayOrder payOrder) {
        // 上游没有查询接口，直接返回
        return QueryRetMsg.waiting();
    }

}
